package com.tiantian.web.controller.task;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tiantian.bean.PageBean;
import com.tiantian.cache.RegionalInformationCache;
import com.tiantian.dao.ReleaseOrderPeriodRepository;
import com.tiantian.domain.Taskgroup;
import com.tiantian.domain.Taskinfobasecommission;
import com.tiantian.domain.Taskinformation;
import com.tiantian.domain.Taskproductinformation;
import com.tiantian.poi.PoiReportBuilder;
import com.tiantian.ret.Result;
import com.tiantian.service.TaskActionIllustrationService;
import com.tiantian.service.TaskinfobasecommissionService;
import com.tiantian.service.TaskinformationService;
import com.tiantian.service.TaskproductinformationService;
import com.tiantian.service.TaskselectvalueaddedservicesService;
import com.tiantian.service.impl.TaskselectvalueaddedservicesServiceImpl.AddServicePrice;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.PageUtil;
import com.tiantian.web.datatables.DataTableReturn;

/**
 * 任务管理
 * 
 * @description
 * @author ynshun
 * @sincere 2016年1月24日 下午10:05:00
 * @version 1.0
 */
@Controller
@RequestMapping("/task")
public class TaskinformationController {
	public static final Logger LOG = LoggerFactory.getLogger(TaskinformationController.class);
	@Resource
	private TaskinformationService taskInfoService;
	@Resource
	private TaskproductinformationService taskproductinformationService;
	@Autowired
	private RegionalInformationCache regionalInformationCache;
	@Autowired
	private ReleaseOrderPeriodRepository releaseOrderPeriodRepository;
	@Autowired
	private TaskActionIllustrationService taskActionIllustrationService;
	@Autowired
	private TaskselectvalueaddedservicesService taskselectvalueaddedservicesService;
	@Autowired
	private TaskinfobasecommissionService taskinfobasecommissionService;

	/**
	 * 任务管理（进入首页页面）
	 * 
	 * @description
	 * @author ynshun
	 * @sincere 2016年1月24日 下午10:04:53
	 * @version 1.0
	 * @param model
	 * @param pageNo
	 * @param pageSize
	 * @param tipBuyersNotes
	 * @return
	 */
	@RequestMapping(value = { "/index", "/manager", "/default", "/", "" })
	public String index() {
		return "/task/taskIndex";
	}

	@ResponseBody
	@RequestMapping(value = { "taskList" })
	public Object taskList(TaskVo taskVo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(taskVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = taskInfoService.list(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	@RequestMapping(value = { "/reportTask" })
	public ModelAndView reportTask(TaskVo taskVo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(taskVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			List<Map<String, Object>> datas = taskInfoService.getReportlist(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("任务ID", "任务状态", "放单总数", "平台类型", "端口", "店铺名称", "任务类型", "任务发布时间", "任务分组", "是否包邮", "主商品名称", "主商品链接", "主商品价格", "主商品数量",
					"附加商品1链接", "附加商品1单价", "附加商品1数量", "附加商品2链接", "附加商品2单价", "附加商品2数量", "基础佣金", "增值服务佣金", "总押金", "已选增值服务");
			if (datas != null) {
				for (Map<String, Object> data : datas) {
					List<String> poiData = new ArrayList<>();
					// 任务ID
					poiData.add((String) data.get("taskid"));
					// 任务状态
					String taskstatus = String.valueOf(data.get("taskstatus"));
					if (StringUtils.equals("taskstatus", "1")) {
						poiData.add("保存未发布");
					} else if (StringUtils.equals(taskstatus, "2")) {
						poiData.add("已发布");
					} else if (StringUtils.equals(taskstatus, "3")) {
						poiData.add("已撤销");
					} else if (StringUtils.equals(taskstatus, "4")) {
						poiData.add("进行中");
					} else {
						poiData.add("已完成");
					}
					// 放单总数
					poiData.add(String.valueOf(data.get("totalorders")));
					// 平台类型
					String platformid = String.valueOf(data.get("platformid"));
					if (StringUtils.equals(platformid, "1")) {
						poiData.add("淘宝/天猫");
					} else {
						poiData.add("京东");
					}
					// 端口 0:淘宝，1：天猫，2：京东,针对手机任务
					String phoneapp = String.valueOf(data.get("phoneapp"));
					if (StringUtils.equals("phoneapp", "0")) {
						poiData.add("淘宝");
					} else if (StringUtils.equals(phoneapp, "1")) {
						poiData.add("天猫");
					} else if (StringUtils.equals(phoneapp, "2")) {
						poiData.add("京东");
					} else {
						poiData.add("");
					}
					// 店铺名称
					poiData.add(String.valueOf(data.get("storename")));
					// "任务类型"
					String tasktypeid = String.valueOf(data.get("tasktypeid"));
					if (StringUtils.equals(tasktypeid, "1")) {
						poiData.add("常规任务");
					} else if (StringUtils.equals(tasktypeid, "2")) {
						poiData.add("特色任务");
					} else if (StringUtils.equals(tasktypeid, "3")) {
						poiData.add("快速任务");
					} else {
						poiData.add("特殊任务");
					}
					// ,"任务发布时间",
					poiData.add(DateFormatUtils.format((Date) data.get("taskpublishedtime"), CommonConstant.TIME_FORMAT_YMDHMS));
					// "任务分组"
					Taskgroup taskgroup = taskInfoService.getTaskgroup(String.valueOf(data.get("taskgroupid")), (String) data.get("businessuserid"));
					if (taskgroup != null) {
						poiData.add(taskgroup.getId().getTaskGroupName());
					} else {
						poiData.add("");
					}
					// ,"是否包邮"
					poiData.add("");
					// ,"主商品名称","主商品链接","主商品价格","主商品数量"
					List<Taskproductinformation> productins = taskproductinformationService.findMajorByTaskId((String) data.get("taskid"));
					if (productins != null && productins.size() > 0) {
						Taskproductinformation productin = productins.get(0);
						poiData.add(productin.getId().getProductName());
						poiData.add(productin.getId().getActivitiesLinks());
						poiData.add(String.valueOf(productin.getId().getPrice().doubleValue()));
						poiData.add(String.valueOf(productin.getId().getPerOrderContainingNum()));
					}
					// "附加商品1链接","附加商品1单价","附加商品1数量",
					List<Taskproductinformation> not_main_productins = taskproductinformationService.findMajorNotMainByTaskId((String) data
							.get("taskid"));
					if (not_main_productins != null && not_main_productins.size() > 0) {
						Taskproductinformation productin = not_main_productins.get(0);
						poiData.add(productin.getId().getActivitiesLinks());
						poiData.add(String.valueOf(productin.getId().getPrice().doubleValue()));
						poiData.add(String.valueOf(productin.getId().getPerOrderContainingNum()));
					} else {
						poiData.add("");
						poiData.add("");
						poiData.add("");
					}

					// "附加商品2链接","附加商品2单价","附加商品2数量"
					if (not_main_productins != null && not_main_productins.size() > 1) {
						Taskproductinformation productin = not_main_productins.get(1);
						poiData.add(productin.getId().getActivitiesLinks());
						poiData.add(String.valueOf(productin.getId().getPrice().doubleValue()));
						poiData.add(String.valueOf(productin.getId().getPerOrderContainingNum()));
					} else {
						poiData.add("");
						poiData.add("");
						poiData.add("");
					}
					// ,,"基础佣金","增值服务佣金","总押金"
					List<Taskinfobasecommission> basecommissions = taskinfobasecommissionService.findByTaskId((String) data.get("taskid"));
					if (basecommissions != null && basecommissions.size() > 0) {
						Taskinfobasecommission basecommission = basecommissions.get(0);
						poiData.add(String.valueOf(basecommission.getBuyersCommission().doubleValue()));
						poiData.add(String.valueOf(basecommission.getPlatformServiceFees().doubleValue()));
						poiData.add(String.valueOf(basecommission.getBusinessesPayBonuses().doubleValue()));
					} else {
						poiData.add("");
						poiData.add("");
						poiData.add("");
					}
					// ,"已选增值服务"
					poiData.add("");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "商家账户_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出商家账户异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	/**
	 * 任务详情（进入详情页面）
	 * 
	 * @description
	 * @author ynshun
	 * @sincere 2016年1月24日 下午10:04:36
	 * @version 1.0
	 * @param model
	 * @param tid
	 * @return
	 */
	@RequestMapping(value = { "/detail/{tid}" })
	public String detail(Model model, @PathVariable("tid") String tid) {

		// 任务信息
		Taskinformation taskinfo = taskInfoService.get(tid);
		model.addAttribute("task", taskinfo);
		// 订单统计
		List<Map<String, Object>> orderCountList = taskInfoService.getOrderCount(tid);
		Map<String, Object> orderCount = new HashMap<String, Object>();
		if (orderCountList != null) {
			for (Map<String, Object> map : orderCountList) {

				orderCount.put("order" + String.valueOf(map.get("orderstatus")), map.get("count"));
			}
		}
		orderCount.put("all", taskInfoService.getAllCount(tid));
		model.addAttribute("orderCount", orderCount);

		// 获取商品列表
		List<Taskproductinformation> productins = taskproductinformationService.findMajorByTaskId(tid);
		model.addAttribute("productin", productins.get(0));

		// 附属商品
		List<Taskproductinformation> not_main_productins = taskproductinformationService.findMajorNotMainByTaskId(tid);
		model.addAttribute("productin_not", not_main_productins);

		// 地区信息
		model.addAttribute("productin_area", regionalInformationCache.getAreaName(productins.get(0).getId().getAreaCode()));
		// 获取搜素关键词
		model.addAttribute("searchKeywords", taskInfoService.getSearchKeyword(tid));

		// 获取防弹时间
		model.addAttribute("releaseOrders", releaseOrderPeriodRepository.findByTaskId(tid));

		// 获取任务操作示意图
		model.addAttribute("taskActions", taskActionIllustrationService.getByTaskId(tid));

		// 获取增值服务
		model.addAttribute("taskAddedservics", taskselectvalueaddedservicesService.getByTaskId(tid));

		// 基础佣金
		List<Taskinfobasecommission> basecommissions = taskinfobasecommissionService.findByTaskId(tid);
		if (basecommissions != null && basecommissions.size() > 0) {
			model.addAttribute("basecommission", basecommissions.get(0));
		}

		// 获取增值服务金额
		Map<String, List<AddServicePrice>> addServicePrices = taskselectvalueaddedservicesService.getPriceByTaskId(tid);
		model.addAttribute("addServicePrice", addServicePrices);
		BigDecimal taskBasePrice = null;
		if (StringUtils.equals("2", taskinfo.getTaskGroupTypeId().getTask2typeId())
				|| StringUtils.equals("7", taskinfo.getTaskGroupTypeId().getTask2typeId())
				|| StringUtils.equals("9", taskinfo.getTaskGroupTypeId().getTask2typeId())) {
			taskBasePrice = new BigDecimal(0);
			if (basecommissions != null && basecommissions.size() > 0) {
				taskBasePrice = taskBasePrice.add(basecommissions.get(0).getBuyersCommission());
			}
			taskBasePrice = taskBasePrice.multiply(new BigDecimal(taskinfo.getTotalOrders()));
		} else {
			taskBasePrice = productins.get(0).getId().getPrice().multiply(new BigDecimal(productins.get(0).getId().getPerOrderContainingNum()));
			for (Taskproductinformation not_main : not_main_productins) {
				taskBasePrice = taskBasePrice.add(not_main.getId().getPrice().multiply(new BigDecimal(not_main.getId().getPerOrderContainingNum())));
			}
			if (basecommissions != null && basecommissions.size() > 0) {
				taskBasePrice = taskBasePrice.add(basecommissions.get(0).getBuyersCommission().add(basecommissions.get(0).getPostage()));
			}
			taskBasePrice = taskBasePrice.multiply(new BigDecimal(taskinfo.getTotalOrders()));
		}
		model.addAttribute("taskBasePrice", taskBasePrice);
		// 增值服务佣金
		BigDecimal allPrice = new BigDecimal(0);
		for (List<AddServicePrice> addServicePrice : addServicePrices.values()) {
			for (AddServicePrice price : addServicePrice) {
				allPrice = allPrice.add(price.getPrice().multiply(new BigDecimal(price.getCount())));
			}
		}
		model.addAttribute("allPrice", allPrice);
		model.addAttribute("totalPrice", allPrice.add(taskBasePrice));
		return "/task/taskDetail";
	}

	@ResponseBody
	@RequestMapping(value = { "/cancelOrder" })
	public Result<Object> cancelOrder(@RequestParam String taskId) {
		return taskInfoService.cancelOrder(taskId);
	}
}
